package com.bwie.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Title:
 * @BelongProjecet zk2
 * @BelongPackage com.bwie.filter
 * @Description:
 * @Copyright 研发一部
 * @Author: Mr.yan
 * @Date: 2024/6/4 10:28
 * @Version V1.0
 */
@Configuration
public class MyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取变量
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getPath().toString();
        String ip = request.getRemoteAddress().getAddress().toString();

        //2.设置白名单
        System.out.println(url);
        if (ip.contains("192.168.158.131")){
            System.out.println("放行");
            return chain.filter(exchange);
        }

        //放行登录接口
        if (url.contains("/user/user/userLogin")){
            System.out.println("放行登录接口");
            return chain.filter(exchange);
        }

        //放行图片上传接口
        if (url.contains("/events/events/uploadFile")){
            System.out.println("放行图片上传接口");
            return chain.filter(exchange);
        }

        //放行视频上传接口
        if (url.contains("/events/events/uploadVideo")){
            System.out.println("放行视频上传接口");
            return chain.filter(exchange);
        }
        //放行投票接口
        if (url.contains("/vote/vote/addRecord")){
            System.out.println("放行视频上传接口");
            return chain.filter(exchange);
        }

        //3.未登录进行、拦截
        String token = request.getHeaders().getFirst("token");
        if (token == null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
